package com.chenyue.cm.controller;

import com.alibaba.fastjson.JSONObject;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.moudules.system.service.SysMenusService;
import com.chenyue.cm.moudules.system.service.SysUserRolesService;
import com.chenyue.cm.moudules.system.utils.PasswordHelper;
import com.chenyue.cm.moudules.system.utils.ShiroUtils;
import com.chenyue.cm.system.domain.SysUsers;
import com.chenyue.cm.system.domain.SysUsersRole;
import com.chenyue.cm.system.domain.SysUsersRoleExample;
import com.chenyue.cm.utils.Result;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @author chenyue
 * @Description: TODO
 * @file:
 * @throws @date 2018/11/14 15:31
 */
@Controller
@Api(value = "个人中心-登录", tags = "个人中心-登录")
@ApiSort(0)
public class LoginController {

    @Autowired
    private SysMenusService sysMenusService;

    @Autowired
    private SysUserRolesService userRoleService;

    /**
     * 登陆
     *
     * @param request
     * @param sysUsers
     * @param model
     * @return
     */
    @Log("登录")
    @RequestMapping(value = "/login.shtml", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "【S0001】用户名密码登录", notes = "用户名密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户名", name = "username", dataType = "string", required = true),
            @ApiImplicitParam(value = "密码", name = "password", dataType = "string", required = true),
    })
    public JSONObject login(HttpServletRequest request, SysUsers sysUsers, @RequestParam(value = "rememberMe", required = false) boolean rememberMe, Model model) {

        String password = PasswordHelper.encryptPassword(sysUsers);
        if (StringUtils.isEmpty(sysUsers.getUsername()) || StringUtils.isEmpty(password)) {
            return Result.returnFailMsg("用户名或密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUsers.getUsername(), sysUsers.getPassword(), rememberMe);
        try {
            // 授权认证
            subject.login(token);
            // 获取用户角色信息
            SysUsersRoleExample aExample = new SysUsersRoleExample();
            aExample.createCriteria().andUserIdEqualTo(ShiroUtils.getUserId());
            List<SysUsersRole> rolelist = userRoleService.selectByExample(aExample);
            List<Map<String, Object>> menuList = new ArrayList<Map<String, Object>>();
            String roleidString = "0";
            if (rolelist.size() > 0) {
                roleidString = rolelist.get(0).getRoleId();
            }
            //根据角色信息获取用户菜单信息
            menuList = sysMenusService.getMainMenuByRoleId(roleidString);
            model.addAttribute("menus", menuList);
            request.setAttribute("user", sysUsers.getUsername());
            return Result.returnMsg(true, "登陆成功", menuList);

        } catch (LockedAccountException lae) {
            lae.printStackTrace();
            token.clear();
            return Result.returnFailMsg("用户已经被锁定不能登录，请与管理员联系！");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            token.clear();
            return Result.returnFailMsg("用户或密码不正确！");
        } catch (Exception e) {
            e.printStackTrace();
            token.clear();
            return Result.returnFailMsg("后台服务异常！");
        }
    }


    /**
     * 登陆
     *
     * @param request
     * @return
     */
    @Log("登录")
    @RequestMapping(value = "/loginPC", method = RequestMethod.POST)
    @ResponseBody
    public Success login(HttpServletRequest request) {

        SysUsers sysUsers = new SysUsers();
        sysUsers.setUsername(request.getParameter("username"));
        sysUsers.setPassword(request.getParameter("password"));

        String password = PasswordHelper.encryptPassword(sysUsers);
        if (StringUtils.isEmpty(sysUsers.getUsername()) || StringUtils.isEmpty(password)) {
            return Success.error("用户名或密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUsers.getUsername(), sysUsers.getPassword(), false);
        try {
            // 授权认证
            subject.login(token);
            // 获取用户角色信息
            SysUsersRoleExample aExample = new SysUsersRoleExample();
            aExample.createCriteria().andUserIdEqualTo(ShiroUtils.getUserId());
            List<SysUsersRole> rolelist = userRoleService.selectByExample(aExample);
            List<Map<String, Object>> menuList = new ArrayList<Map<String, Object>>();
            String roleidString = "0";
            if (rolelist.size() > 0) {
                roleidString = rolelist.get(0).getRoleId();
            }
            //根据用户所属角色获取菜单列表
            menuList = sysMenusService.getMainMenuByRoleId(roleidString);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("token", subject.getSession().getId().toString());
            resultMap.put("menuInfo", menuList);
            return Success.success(resultMap);
        } catch (LockedAccountException lae) {
            lae.printStackTrace();
            token.clear();
            return Success.error("用户已经被锁定不能登录，请与管理员联系！");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            token.clear();
            return Success.error("用户或密码不正确！");
        } catch (Exception e) {
            e.printStackTrace();
            token.clear();
            return Success.error("后台服务异常！");
        }
    }


    /**
     * 【API】  ---- 获取用户信息
     *
     * @return
     */
    @Log("获取登录信息")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Success getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        SysUsers sysUser = ShiroUtils.getUser();

        String roleId = "0";
        SysUsersRoleExample aExample = new SysUsersRoleExample();
        aExample.createCriteria().andUserIdEqualTo(ShiroUtils.getUserId());
        List<SysUsersRole> rolelist = userRoleService.selectByExample(aExample);
        if (rolelist.size() > 0) {
            roleId = rolelist.get(0).getRoleId();
        }
        sysUser.setRemark(roleId);

        return Success.success(sysUser);
    }


    /**
     * 【API】  ---- 退出登录
     *
     * @param request
     * @param response
     * @return
     */
    @Log("注销")
    @PostMapping(value = "/logoutPC")
    @ResponseBody
    @ApiOperation(value = "【S0005】注销登录", notes = "注销登录")
    public Success logout(HttpServletRequest request, HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        // 注销
        subject.logout();
        return Success.success("退出成功");
    }


    /**
     * 重定向至登录页面
     *
     * @return
     */
    @RequestMapping(value = "/login.shtml", method = RequestMethod.GET)
    public String toLogin() {
        return "redirect:/master/login";
    }


    /**
     * 退出登录
     *
     * @return
     */
    @Log("注销登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        // 注销
        subject.logout();
        return "redirect:/master/login";
    }

}
